{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一段程序，将1（D：）zy8文件夹下的Contest Result文件夹中Contest Result.html中的内容保存为本地excel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data has been successfully saved to D:\\zy8\\Contest Result\\Contest Result.xlsx\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from bs4 import BeautifulSoup\n",
    "import pandas as pd\n",
    "\n",
    "# 定义文件路径\n",
    "html_file_path = r'D:\\zy8\\Contest Result\\Contest Result.html'\n",
    "excel_file_path = r'D:\\zy8\\Contest Result\\Contest Result.xlsx'\n",
    "\n",
    "# 读取 HTML 文件内容\n",
    "with open(html_file_path, 'r', encoding='utf-8') as file:\n",
    "    html_content = file.read()\n",
    "\n",
    "# 使用 BeautifulSoup 解析 HTML\n",
    "soup = BeautifulSoup(html_content, 'html.parser')\n",
    "\n",
    "# 假设 HTML 中的数据在一个 <table> 标签内，我们需要找到这个表格\n",
    "# 注意：这里的 'table' 是一个示例选择器，你需要根据实际情况修改它\n",
    "# 如果表格有特定的 id 或 class，你可以使用 '#id' 或 '.class' 来选择\n",
    "table = soup.find('table')  # 修改为 soup.find('table', {'id': 'specific-id'}) 或其他选择器\n",
    "\n",
    "# 提取表格中的行和列\n",
    "rows = table.find_all('tr')\n",
    "data = []\n",
    "for row in rows:\n",
    "    cells = row.find_all(['td', 'th'])  # 提取单元格，包括表头和普通单元格\n",
    "    row_data = [cell.get_text(strip=True) for cell in cells]  # 获取单元格文本并去除前后空白\n",
    "    data.append(row_data)\n",
    "\n",
    "# 创建 DataFrame\n",
    "df = pd.DataFrame(data[1:], columns=data[0])  # 假设第一行是列名，其余行是数据\n",
    "\n",
    "# 将 DataFrame 保存为 Excel 文件\n",
    "df.to_excel(excel_file_path, index=False)\n",
    "\n",
    "print(f\"Data has been successfully saved to {excel_file_path}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
